package com.shut.vehicle.verification.aspect;



import com.shut.vehicle.verification.Container;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Collection;

/**
 * @author 卢斌
 */
public class ContainerHandler implements ConstraintValidator<Container, Collection<?>> {

    private boolean canBeNull;

    private boolean canHasNull;

    private int minSize;

    private int maxSize;

    @Override
    public void initialize(Container constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        canBeNull = constraintAnnotation.canBeNull();
        canHasNull = constraintAnnotation.canHasNull();
        minSize = constraintAnnotation.minSize();
        maxSize = constraintAnnotation.maxSize();
        if (minSize < 0) {
            minSize = 0;
        }
        if (maxSize < minSize) {
            maxSize = minSize;
        }
    }

    @Override
    public boolean isValid(Collection<?> objects, ConstraintValidatorContext constraintValidatorContext) {
        if (!canBeNull && objects == null) {
            return false;
        }
        if (objects != null) {
            if (! canHasNull) {
                if (objects.contains(null)) {
                    return false;
                }
            }
            return objects.size() <= maxSize && objects.size() >= minSize;
        }
        return true;
    }


}